//
//  SendMealAddressAndTimeController.m
//  FD
//
//  Created by xiaofang wang on 2018/11/2.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//  送餐地址和时间
// UITableViewHeaderFooterView
//UITableViewHeaderFooterView
//接口 /user/shipping_address/list
#import "SendMealAddressAndTimeController.h"
//view
#import "WSSendMealTimeFooterView.h"
#import "WSSongCanCell.h"
#import "WSSendMealTimeSectionHeaderView.h"
#import "BRPickerView.h" //日期选择器

//model
#import "MyAddressModel.h"

//controller
#import "MyAddAddressViewControllerXin.h" //2019-1-7

#import "EditSongCanAddressController.h" //编辑送餐地址 继承至 MyAddNewAddressController  需要将当前的信息传递过去。

@interface SendMealAddressAndTimeController ()
<UITableViewDelegate,UITableViewDataSource>
{
    //记录选择的收货地址模型
    MyAddressModel *_selectedAddressModel;
}

/**确认按钮*/
@property (nonatomic, strong) UIButton *sureBtn;
/**uitableView*/
@property (nonatomic, strong) UITableView *tableView;
/**2.表位*/
@property (nonatomic, strong) WSSendMealTimeFooterView *footerView;
/**收货地址数组*/
@property (nonatomic, strong) NSMutableArray *dataArr;
/**11-15 是否是编辑状态*/
@property (nonatomic) BOOL isEdit;

@end

@implementation SendMealAddressAndTimeController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupNav];
    [self setupView];
    
    self.isEdit = NO;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadData]; //视图更新后显示界面。
}

- (void)setupView {
    
    self.tableView.frame = self.view.bounds;
    //底部留出40px给按钮
    
    CGFloat sureBtnH = 50;
    CGFloat bottom = sureBtnH + FD_TabbarSafeBottomMargin; //适配iphoneX
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, bottom, 0);
    
    [self.view addSubview:self.tableView];
    
    //确认
    self.sureBtn.frame = CGRectMake(0, SCREEN_HEIGHT - bottom, SCREEN_WIDTH, sureBtnH);
    [self.view addSubview:self.sureBtn];
}



- (void)setupNav {
    self.view.backgroundColor = kMainLightGrayColor;
    
    UIButton *rightBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [rightBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    rightBtn.frame = CGRectMake(0, 0, 90, 40);
    rightBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight; //右边对齐
    
    rightBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    //添加点击事件
    [rightBtn addTarget:self action:@selector(clickRightBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self __internationalWithBtn:rightBtn];
}

//国际化
- (void)__internationalWithBtn:(UIButton *)rightBtn{
    NSString *addressAndTimestr = NSLocalizedString(DeliveryAddressAndTime, @"送餐地址和时间");
    NSString *wcstr = NSLocalizedString(Completed, @"完成");
    NSString *managerStr =  NSLocalizedString(Manager, @"管理");
    
    self.navigationItem.title = addressAndTimestr;
    [rightBtn setTitle:managerStr forState:(UIControlStateNormal)];
    [rightBtn setTitle:wcstr forState:(UIControlStateSelected)];
}

- (void)clickRightBtnAction:(UIButton *)btn
{
    btn.selected = !btn.selected;
    
//    FDLog(@"%@",btn.titleLabel.text);
    self.isEdit = btn.selected;
    FDLog(@"====：%@",self.isEdit ? @"完成" : @"管理");
    [self.tableView reloadData];
}



#pragma mark - getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStyleGrouped)]; //取消粘连效果
        //代理
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        //注册cell
        [_tableView registerNib:[UINib nibWithNibName:@"WSSongCanCell" bundle:nil] forCellReuseIdentifier:@"WSSongCanCell"];
        
        //注册区头
        [_tableView registerClass:[WSSendMealTimeSectionHeaderView class] forHeaderFooterViewReuseIdentifier:@"WSSendMealTimeSectionHeaderView"];
    }
    return _tableView;
}

- (WSSendMealTimeFooterView *)footerView {
    if (!_footerView) {
        _footerView = [[WSSendMealTimeFooterView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 120)];
        
        //最小时间为当前系统时间
        NSDate *currentDate = [NSDate date];
        NSDate *minDate = [NSDate br_setHour:currentDate.br_hour minute:currentDate.br_minute];
        FDLog(@"当前系统时间: %@",minDate);
        
        NSDate *maxDate = [NSDate br_setHour:23 minute:59];
        
        __weak typeof(self) weakSelf = self;
        //选择 预约送达 时间
        _footerView.clickYuYueBlock = ^{
            [BRDatePickerView showDatePickerWithTitle:@"" dateType:(BRDatePickerModeHM) defaultSelValue:@"" minDate:minDate maxDate:maxDate isAutoSelect:NO themeColor:[UIColor blackColor] resultBlock:^(NSString *selectValue) {
                FDLog(@"选择的时间是:%@",selectValue);
                //更新文字
                [weakSelf.footerView updateYuYueTimeStr:selectValue];
            }];
        };
    }
    return _footerView;
}


- (UIButton *)sureBtn {
    if (!_sureBtn) {
        _sureBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _sureBtn.backgroundColor = kMainRedColor;
        //国际化
        NSString *sureStr = NSLocalizedString(Sure, @"确认");
        [_sureBtn setTitle:sureStr forState:(UIControlStateNormal)];
        [_sureBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        [_sureBtn addTarget:self action:@selector(clickSureAction:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _sureBtn;
}
- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}


#pragma mark - 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WSSongCanCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WSSongCanCell"];
    
    MyAddressModel *currentAddressModel = self.dataArr[indexPath.row];
    
    cell.addressModel = currentAddressModel;
    
    [cell updateUIWithIsEdit:self.isEdit];
  
    cell.clickDeleteBlcok = ^{
        FDLog(@"点击 删除按钮");
        [self removeAddressAlertWithAdressId:currentAddressModel.addressId];
    };
    cell.clickEditBlock = ^{
        FDLog(@"点击 编辑按钮");
        //跳转编辑送餐地址，同时把当前的数据传递过去。
        EditSongCanAddressController *editAddressVC = [[EditSongCanAddressController alloc] init];
        editAddressVC.addressModel = currentAddressModel;
        editAddressVC.fromWhichVC = 1;//导航条下移64问题
        [self.navigationController pushViewController:editAddressVC animated:YES];
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

#pragma mark - 点击事件 单选
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    FDLog(@"%ld--%ld",indexPath.section,indexPath.row);
    
    //排他思想
    for (MyAddressModel *model in self.dataArr) {
        model.selected = NO;
    }
    
    //当前的标记为选中状态。
    MyAddressModel *selectedModel  = self.dataArr[indexPath.row];
    selectedModel.selected = YES; //标记为选中状
    [self.tableView reloadData]; //刷新数据
    
    //标记选择中的地址模型
    _selectedAddressModel = selectedModel;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    WSSendMealTimeSectionHeaderView *sectionHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"WSSendMealTimeSectionHeaderView"];
    
    //跳转新增收货地址页面
    sectionHeaderView.wsSendSendMealTimeSectionHeaderViewClickAddBlock = ^{
        MyAddAddressViewControllerXin *xinAddressVC = [[MyAddAddressViewControllerXin alloc] init];
        xinAddressVC.fromWhichVC = 1;//标记从那过来的。
        [self.navigationController pushViewController:xinAddressVC animated:YES];
    };
    
    return sectionHeaderView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44 + 10; //10px线
}


#pragma mark - 确定
- (void)clickSureAction:(UIButton *)sureBtn
{
    //回调收回地址模型
    if (_selectedAddressModel) {
        self.addressBlock(_selectedAddressModel);
        
        [self.navigationController popViewControllerAnimated:YES]; //返回
    }else {
        [JRToast showWithText:NSLocalizedString(Order_chooseAddress, @"请选择送餐地址")];
    }
}

#pragma mark - loadData
- (void)loadData {
    
    [MBProgressHUD fd_showHUDToView:self.view]; //菊花
    [FDHttpAPi requestUserShouHuoAddressSucccessBlock:^(id responseObjc) {
        
        [MBProgressHUD fd_hideHUDFromView:self.view]; //影藏菊花
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
        
            
            //解析数据
            NSArray *arr = responseObjc[@"data"];
            //清空之前的所有数据
            [self.dataArr removeAllObjects];
            
            for (NSDictionary *dic in arr) {
                MyAddressModel *model = [MyAddressModel mj_objectWithKeyValues:dic];
                [self.dataArr addObject:model];
            }

            //刷新数据
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } fialBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
        [MBProgressHUD fd_hideHUDFromView:self.view]; //影藏菊花
    }];
}

//移除收货地址
- (void)removeAddressAlertWithAdressId:(NSNumber *)addressId {
    
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedString(L_Delete, @"删除") message:NSLocalizedString(L_ShiFouShanChuGaiDiZhi, @"是否删除该地址") preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(Cancel, @"取消") style:(UIAlertActionStyleCancel) handler:nil];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(L_Confirm, @"确定") style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        [self requestRemoveAddressWithId:addressId];
    }];
    [alertVC addAction:cancelAction];
    [alertVC addAction:sureAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}


- (void)requestRemoveAddressWithId:(NSNumber *)addressId {
    [FDHttpAPi requestUserAddressRemoveWithID:addressId succesBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            
            FDLog(@"当前线程: %@",[NSThread currentThread]);

            [self loadData]; //重新请求
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}
@end
